package com.github.pig.admin.controller.zhgl.houseowner;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.github.pig.admin.model.device.GuardDevice;
import com.github.pig.admin.model.dto.HouseOwnerDTO;
import com.github.pig.admin.model.entity.PaymentRecord;
import com.github.pig.admin.model.entity.SysRole;
import com.github.pig.admin.model.entity.SysUserRole;
import com.github.pig.admin.model.zhgl.building.CommunityBuilding;
import com.github.pig.admin.model.zhgl.community.CommunityInfo;
import com.github.pig.admin.model.zhgl.house.UnitHouse;
import com.github.pig.admin.model.zhgl.house.UnitHouseBean;
import com.github.pig.admin.model.zhgl.houseowner.HouseOwner;
import com.github.pig.admin.model.zhgl.unit.BuildingUnit;
import com.github.pig.admin.service.sys.PaymentRecordService;
import com.github.pig.admin.service.sys.SysRoleService;
import com.github.pig.admin.service.sys.SysUserRoleService;
import com.github.pig.admin.service.zhgl.building.ICommunityBuildingService;
import com.github.pig.admin.service.zhgl.community.ICommunityInfoService;
import com.github.pig.admin.service.zhgl.house.IUnitHouseService;
import com.github.pig.admin.service.zhgl.houseowner.IHouseOwnerService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.util.DateTools;
import com.netflix.discovery.converters.Auto;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.github.pig.common.constant.CommonConstant;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.common.util.Query;
import com.github.pig.common.util.R;
import com.github.pig.common.web.BaseController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 业主基本信息表 前端控制器
 * </p>
 *
 * @author lxm
 * @since 2018-06-20
 */
@RestController
@RequestMapping("/houseOwner")
public class HouseOwnerController extends BaseController {
    @Autowired
    private IHouseOwnerService houseOwnerService;
    @Autowired
    private IUnitHouseService unitHouseService;
    @Resource
    private ICommunityBuildingService communityBuildingService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysRoleService sysRoleService;
    @Autowired
    private ICommunityInfoService communityService;
    @Autowired
    private PaymentRecordService recordService;



    /**
     * 客户经理根据身份证号姓名查询
     * @return HouseOwner
     */
    @GetMapping("/getByIdCard")
    public AjaxJson getByIdCard(@RequestParam("idCard")String idCard,@RequestParam("name")String name) {
        AjaxJson json = new AjaxJson();
        try{
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
            wrapper.eq("card_number",idCard);
            wrapper.eq("name",name);
            List<HouseOwnerDTO> dtoList = new ArrayList<>();
            List<HouseOwner> list = houseOwnerService.selectList(wrapper);
          /*  List<String> houseIds = list.stream().map(HouseOwner::getHouseId).collect(Collectors.toList());
            unitHouseService.selectBatchIds(houseIds)
                    .stream().map(h ->{
                HouseOwnerDTO dto = new HouseOwnerDTO();
                dto.set
                return dto;
            }).collect(Collectors.toList());*/
            for(HouseOwner owner : list){
                HouseOwnerDTO dto = new HouseOwnerDTO();
                UnitHouse h = unitHouseService.selectById(owner.getHouseId());
                //取整
                if(h.getBuildSize()!=null && h.getBuildSize()!=0){
                    dto.setArea("约 "+ (int)(h.getBuildSize()/10)*10+" ㎡");
                }else{
                    dto.setArea("面积不详");
                }
                wrapper = new EntityWrapper();
                wrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
                wrapper.eq("house_id",owner.getHouseId());
                wrapper.or("relation","4",5);
                Integer count = unitHouseService.selectCount(wrapper);
                if(count>0){
                    dto.setMarriage("已婚");
                }else{
                    dto.setMarriage("未婚");
                }
                wrapper = new EntityWrapper();
                wrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
                wrapper.eq("house_id",owner.getHouseId());
                wrapper.or("relation","3","4","5");
                count = unitHouseService.selectCount(wrapper);
                dto.setFamilyCount(count);
                //TODO 获取开门异常次数  晚11--次日5
                dto.setAccess_last((int)(Math.random()*10));
                dto.setAccess_last_six((int)(Math.random()*100));
                CommunityInfo info = communityService.selectById(h.getCommunityId());
                dto.setCommunityName(info==null ? "":info.getName());
                dto.setHouseType(h.getHouseType());
                dto.setIdCard(idCard);
                dto.setUserName(name);

                if(h.getProertyEndtime().before(new Date())){
                    dto.setProperty(true);
                }else{
                    dto.setProperty(false);
                }
                //是否常住  根据水电暖缴费情况
                wrapper = new EntityWrapper();
                wrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
                wrapper.eq("house_id",owner.getHouseId());
               List records =  recordService.selectList(wrapper);
                if(records!=null && records.size()>0){
                    dto.setResidence(true);
                }else{
                    dto.setResidence(true);
                }
                dtoList.add(dto);
            }
            json.setSuccess(true);
            json.setObj(dtoList);
        }catch(Exception e){
            e.printStackTrace();
            logger.error("",e);
            json.setSuccess(false);
            json.setMsg(e.getMessage());
        }
        return json;
    }

    public static void main(String[] args) {
        System.out.println((int)(Math.random()*100));
    }

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return HouseOwner
    */
    @GetMapping("/{id}")
    public R<HouseOwner> get(@PathVariable Integer id) {
        return new R<>(houseOwnerService.selectById(id));
    }


    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @RequestMapping("/page")
    public Page page(@RequestParam Map<String, Object> params,HouseOwner houseOwner) {
        Page<HouseOwner> page = new Page<HouseOwner>(Integer.parseInt(params.getOrDefault("page", 1).toString())
                , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
        return houseOwnerService.querHouseOwnerGrid(page,houseOwner);
    }



    @RequestMapping("/upload")
    public AjaxJson upload(ModelMap modelMap, HttpServletRequest request, String communityId){
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        HashMap<String,String> uploadMap = new HashMap();
        //所有的角色ID
        StringBuilder sb = new StringBuilder();
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setImportFields(HouseOwner.heads);
            try {
                List<HouseOwner> list = ExcelImportUtil.importExcel(file.getInputStream(),HouseOwner.class,params);
                if(list==null||list.size()==0){
                    j.setMsg("文件空内容。");
                    return j;
                }
                List<UnitHouse> unitHousesList = new ArrayList<>();
                List<HouseOwner> insertList = new ArrayList<>();
                for(HouseOwner bean : list){
                    UnitHouseBean unitHouseBean = houseOwnerService.getUnitHouseBean(bean.getBuildingName(),bean.getUnitName(),bean.getHouseName(),communityId);
                    if(unitHouseBean==null){
                        continue;
                    }
                    bean.setHouseId(unitHouseBean.getId());
                    if(BuildingUnit.BUILDING_TYPE_HOUSE.equals(unitHouseBean.getBuildingType())){
                        if(uploadMap.containsKey(unitHouseBean.getId())){
                            continue;
                        }
                        uploadMap.put(unitHouseBean.getId(),unitHouseBean.getId());
                    }

                    bean.setRelation("1");
                    if(StringUtils.isNotEmpty(bean.getSex())){
                        bean.setSex(("男".equals(bean.getSex())?"0":"1"));
                    }
                    //角色名称维护
                    if(StringUtils.isNotEmpty(bean.getRoleId())){
                        sb.append(bean.getRoleId()+",");

                        String[] roleIds = bean.getRoleId().split(",");
                        StringBuffer roleName = new StringBuffer();
                        for(String roleId : roleIds){
                            SysRole sysRole = sysRoleService.selectById(roleId);
                            if(sysRole!=null ){
                                roleName.append(sysRole.getRoleName()+",");
                            }
                        }
                        roleName.deleteCharAt(roleName.lastIndexOf(","));
                        bean.setRoleName(roleName.toString());
                    }
                    UnitHouse unitHouse = unitHouseService.selectById(unitHouseBean.getId());
                    unitHouse.setStatus("2");
                    unitHousesList.add(unitHouse);
                    insertList.add(bean);
                }
               j =  houseOwnerService.batchAddOwner(insertList,unitHousesList,sb.length()==0 ?"":sb.substring(0,sb.length()-1),list.size());
            } catch (Exception e) {
                e.printStackTrace();
                j.setSuccess(false);
                j.setMsg("文件导入失败！"+e.getMessage());
            }finally{
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

    /**
     * 添加
     * @param  houseOwner  实体
     * @return success/false
     */
    @RequestMapping("/doAdd")
    public AjaxJson add(@RequestBody HouseOwner houseOwner) {
        AjaxJson json=new AjaxJson();
        try{
            if(existHouseOwner(houseOwner.getHouseId())){
                json.setSuccess(false);
                json.setMsg("添加失败,该房屋已经存在户主。");
                return  json;
            }
           json =  houseOwnerService.addOwner(houseOwner);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("添加业主：",e);
            json.setSuccess(false);
            json.setMsg("添加失败,"+e.getMessage());
        }
        return json;
    }

    /**
     * 判断房屋是否已经添加业主
     */
    public boolean existHouseOwner(String houseId){
        CommunityBuilding communityBuilding = communityBuildingService.selectBuildingByHouseId(houseId);
        if(CommonConstant.BUILDING_TYPE.equals(communityBuilding.getBuildingType())){
            return false;
        }
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("house_id",houseId);
        entityWrapper.eq("relation","1");
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        List result = houseOwnerService.selectList(entityWrapper);
        if(result!=null&&result.size()>0){
            return true;
        }
        return false;
    }

    /**
     * 移交房屋
     * @param houseOwner
     * @return
     */
    @RequestMapping("/handOverHouse")
    public AjaxJson handOverHouse(@RequestBody HouseOwner houseOwner) {
        AjaxJson json=new AjaxJson();
        try{
            CommunityBuilding communityBuilding = communityBuildingService.selectBuildingByHouseId(houseOwner.getHouseId());
            if(CommonConstant.BUILDING_TYPE.equals(communityBuilding.getBuildingType())){
                json.setSuccess(false);
                json.setMsg("移交失败,商用楼房不支持移交。");
                return json;
            }
            houseOwnerService.handOverHouse(houseOwner,json);
            if(!json.isSuccess()){
                return  json;
            }
            json.setSuccess(true);
            json.setMsg("移交成功");
        }catch (Exception e){
            e.printStackTrace();
            json.setSuccess(false);
            json.setMsg("移交失败。");
        }
        return json;
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @RequestMapping("/doDel")
    public AjaxJson delete( String id) {
        AjaxJson json=new AjaxJson();
        try{
            HouseOwner houseOwner = houseOwnerService.selectById(id);
            houseOwner.setDelFlag(CommonConstant.STATUS_DEL);
            boolean flag = houseOwnerService.delOwner(houseOwner);
            json.setSuccess(flag);
            if(flag){
                json.setMsg("删除成功!");

            }else{
                json.setMsg("删除失败!");
            }
        }catch(Exception e){
            e.printStackTrace();
            logger.error("删除业主",e);
            json.setSuccess(false);
            json.setMsg("删除失败!");
        }

        return json;
    }

    @RequestMapping("/doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids){
        AjaxJson json=new AjaxJson();
        boolean flag = houseOwnerService.delOwnerList(houseOwnerService.selectBatchIds(Arrays.asList(ids.split(","))));
        json.setSuccess(flag);
        if(flag){
            json.setMsg("删除成功!");

        }else{
            json.setMsg("删除失败!");
        }
        return json;
    }

    /**
     * 编辑
     * @param  houseOwner  实体
     * @return success/false
     */
    @RequestMapping("/doUpdate")
    public AjaxJson edit(@RequestBody HouseOwner houseOwner) {
        AjaxJson json = new AjaxJson();
        try{
            json = houseOwnerService.updateOwner(houseOwner);
        }catch (Exception e){
            logger.error("业主信息更新",e);
            e.printStackTrace();
            json.setMsg("业主信息更新失败，"+e.getMessage());
            json.setSuccess(false);
        }
        return json;
    }

    @RequestMapping("/queryUnitHouse")
    public List<UnitHouseBean> queryUnitHouse(UnitHouseBean unithouse) {
        return houseOwnerService.queryUnitHouse(unithouse);
    }

    /**
     * 根据房屋获取业主列表
     * @return
     */
    @RequestMapping("/getHouseOwners/{houseId}")
    @ResponseBody
    public List<HouseOwner> ownerList(@PathVariable String houseId) {
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("house_id",houseId);
        entityWrapper.eq("del_flag",CommonConstant.STATUS_NORMAL);
        return houseOwnerService.selectList(entityWrapper);
    }
}
